package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Set;


@Component
@EnableConfigurationProperties(AuthProperties.class)
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher=new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        if(isExclude(request.getPath().toString())){
            //放行exclude中的路径
            return chain.filter(exchange);
        }
        String token=null;
        List<String> authorization = request.getHeaders().get("authorization");
        if(!CollUtils.isEmpty(authorization)){
            token=authorization.get(0);
        }
        Long userId=null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            //无效token
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
//        System.out.println("userId:"+userId);
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("user-info", userInfo))
                .build();
        return chain.filter(ex);

    }

    private boolean isExclude(String path) {
        List<String> paths = authProperties.getExcludePaths();
        for (String excludePath : paths) {
            if(antPathMatcher.match(excludePath,path)){
                return true;
            }
        }
        return false;

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
